<?php

declare (strict_types=1);

namespace app\listener\order;

use app\event\CouponOrderUpdate;
use app\model\AgentBalanceLog;
use app\model\AgentFinanceDaily;
use app\model\CouponOrder;
use Carbon\Carbon;

class OrderDayStatListener
{


    public $couponOrder;

    /**
     * 事件监听处理
     * @return mixed
     * @var CouponOrderUpdate $event
     */
    public function handle($event)
    {

        /**
         * @var CouponOrder $couponOrder
         */
        $couponOrder = $event->couponOrder;

        $this->couponOrder = $couponOrder;

        $statOrder = $this->getOrderStat($event); //当天预算金额

        $profit = $statOrder['profit'];
        $order_num = $statOrder['order_num'];
        $pay_amount = $statOrder['pay_amount'];

        $settle_amount = $this->getDayAgentBalanceLogAmount($event); //当天已结算金额


        $getExceptSettleEstimate = $this->getExceptSettleEstimate($event); //当日未结算

        $getExceptSettleEstimateAmount = $getExceptSettleEstimate['profit'] ?? 0;

        if (empty($profit) && empty($settle_amount)) {
            return;
        }

        AgentFinanceDaily::findOrCreate([
            'agent_id' => $couponOrder->agent_id,
            'dateymd' => $event->date,
        ], [
            'estimate_amount' => $profit,
            'settle_amount' => $settle_amount,
            'order_num' => $order_num,
            'trade_amount' => $pay_amount,
            'except_settle_estimate_amount' => $getExceptSettleEstimateAmount,
        ]);

    }


    /**
     * 当天该代理的预估佣金
     * @param $event
     * @return int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderStat($event)
    {
        /**
         * @var CouponOrderUpdate $event
         */
        //该天的预估佣金
        $couponStat = CouponOrder::query()
            ->field([
                'sum(profit) as profit',//预估收入
                'count(id) as order_num', //订单
                'sum(pay_amount) as pay_amount',
            ])
            ->where([
                'agent_id' => $event->couponOrder->agent_id,
            ])
            ->estimate() //预估收入

            ->whereBetweenTime('order_created_at', $event->date, Carbon::parse($event->date)->endOfDay())
            ->find()->toArray();

        return $couponStat;
    }


    /**
     * 当天该代理的预估佣金
     * @param $event
     * @return int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getExceptSettleEstimate($event)
    {
        /**
         * @var CouponOrderUpdate $event
         */
        //该天的预估佣金
        $couponStat = CouponOrder::query()
            ->field([
                'sum(profit) as profit',//预估收入
            ])
            ->where([
                'agent_id' => $event->couponOrder->agent_id,
            ])

            ->exceptSettleEstimate() //扣除已结算的

            ->whereBetweenTime('order_created_at', $event->date, Carbon::parse($event->date)->endOfDay())
            ->find()->toArray();

        return $couponStat;
    }


    /**
     * 结算金额
     * @param $event
     * @return int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDayAgentBalanceLogAmount($event)
    {
        /**
         * @var CouponOrderUpdate $event
         */
        //该天的结算佣金
        $agentBalanceLog = AgentBalanceLog::query()
            ->field([
                'sum(amount) as amount'
            ])
            ->where([
                'agent_id' => $event->couponOrder->agent_id,
            ])
            ->whereBetweenTime('created_at', $event->date, Carbon::parse($event->date)->endOfDay())
            ->find()->toArray();

        return $agentBalanceLog['amount'] ?? 0;

    }


}
